package com.cloud.file.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.lock.LockInfo;
import com.baomidou.lock.LockTemplate;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloud.api.file.enums.FileStatusEnum;
import com.cloud.api.file.model.SysFile;
import com.cloud.common.core.util.JsonUtil;
import com.cloud.file.service.SysFileService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@EnableScheduling
@RequiredArgsConstructor
@Slf4j
public class FileTask {


    private final SysFileService sysFileService;
    private final FileStorageService fileStorageService;
    private final LockTemplate lockTemplate;

    /**
     * 清除临时文件(30天之前的)
     * 由于底层使用的是redisTemplate，存在锁超时的问题
     * 如果严格要求执行顺序的话，需要接入redission，使用redission的看门狗机制，解决锁超时的问题
     */
    @Scheduled(cron="0 0 1 * * ?")
    public void deleteTmpFile(){

        String key="FileTask:deleteTmpFile";
        //锁失效时间1个小时，获取锁失败3s
        LockInfo lockInfo=lockTemplate.lock(key,3600*1000,3000);
        if(lockInfo==null){
            log.info("FileTask.deleteTmpFile未获取到锁，任务结束");
            return;
        }
        try {
            log.info("FileTask.deleteTmpFile任务开始**********************");
            //删除文件
            List<SysFile> fileList=sysFileService.list(new LambdaQueryWrapper<SysFile>()
                            .eq(SysFile::getFileStstus, FileStatusEnum.TMP)
                .lt(SysFile::getCreateTime, DateUtil.offsetDay(new Date(),30))
            );
            if(CollUtil.isNotEmpty(fileList)){
                fileList.forEach(file->{
                    fileStorageService.delete(file.getUrl());
                });
            }
            log.info(JsonUtil.toJsonString(fileList));
        }catch (Exception e){
            log.error("FileTask.deleteTmpFile任务执行失败",e);
        }finally {
            lockTemplate.releaseLock(lockInfo);
        }
        log.info("FileTask.deleteTmpFile任务结束**********************");
    }
}
